/**
 * @desc
 * 模板打包JS webpack内置.随后会包装成为一个命令
 *
 * 实际把Bar与-P文件打包压缩 ..
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/4/18
 **/
'use strict';
var webpack = require('webpack');
let fse = require('fs-extra');
let path = require('path');
let co  =require('co');


// var ossConfig = require('../config').ossConfig;
// var ossClient= require('@qianmi/x-site-common/util/oss').getOssClient(ossConfig);
var util   = require('./_util');

// var ossLoadUpdateService= require('@qianmi/x-site-common/service/oss-load-update-service')(ossClient);

var ExtractTextPlugin = require("extract-text-webpack-plugin");
let basicConfigFactory =require('./webpack.config.factory')();

let templateUtil = require('./template-util');
let isWatchMode = false;// true false

console.log("开始编译-----------------------------------");

/**
 * 要打包的文件路径信息
 * @type {Array}
 */
let templatePathArray=require('../tpl-path-cfg');
let tempConfigPath  =path.join(__dirname,'./web_modules/x-site-ui/template/pc-demo1/template-config.json');

let prodExtraPlugin=[];
let outputJsFileNameTpl ='[name].js';
let outputCssFileNameTpl ='[name].css';
// if(envCode === 'prod'){ //默认不进行压缩操作..

     outputJsFileNameTpl ='[name]-[hash].js';
     outputCssFileNameTpl ='[name]-[hash].css';

    prodExtraPlugin  =[
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })];
// }

 
// let aliPrefix ="http://oss-hz.qianmi.com/x-site/"+envCode+"/public/";

co(function * () {
    let toCompileTem = [];
    let templateIndex  = [];
    for(let i =0,ilen=templatePathArray.length ; i<ilen; i++){
       let _templateConfig = yield templateUtil.generateTplInfo(templatePathArray[i]);
        toCompileTem.push(_templateConfig);
        
        let {templateJs,templateCss} = yield  util.generateTemplateConfigContent({templateConfig:_templateConfig});
        templateIndex.push(extraTemplateInfo(_templateConfig));
        let templatePath  = path.join(__dirname,'../dist/tplRepo',_templateConfig.templateName);
        fse.outputFileSync(templatePath+".js", templateJs);
        fse.outputFileSync(templatePath+".css", templateCss);
    }
    fse.outputJSONSync(path.join(__dirname,'../dist/templateIndex.json'), templateIndex);
}).then(()=>{
},err=>{
    console.error(err.stack);
});


/**
 * 处理webpack打包后,的步骤
 * @param stats
 */
function * dealWebpackResult (tempConfigArray,stats){

    console.log('打包成功. 相关文件已处理');
    //把JS css 上传到阿里云
    //从这里可以拿到最后生成的结果;; 并更新模板索引文件上传
    //console.dir(stats);
    let assetsResult  = stats.compilation.assets;

    //分模板//

    let tempMap = {};
    for(let i =0,ilen=tempConfigArray.length ; i<ilen; i++){
        tempMap[tempConfigArray[i].templateName] = {
            templateConfig:tempConfigArray[i],
            jsFile:"",
            cssFile:""
        };
    }



    for(let fileNameKey in  assetsResult){
        //从名字中提取pageCode
        let tempCode  =    extraTempCodeFromAssets(fileNameKey,{
            hash:stats.hash
        });
        if(fileNameKey.includes('.js')){
            if(!tempMap[tempCode]){
                console.log(tempCode);
            }
            tempMap[tempCode].jsFile =assetsResult[fileNameKey].existsAt;
        } else  if(fileNameKey.includes('.css')){
            if(!tempMap[tempCode]){
                console.log(tempCode);
            }
            tempMap[tempCode].cssFile =assetsResult[fileNameKey].existsAt;
        }
    }

    for (let tempCode in tempMap) {
        try{
            yield  checkTemplateInfo(tempMap[tempCode].templateConfig,{
                jsFile:tempMap[tempCode].jsFile,
                cssFile:tempMap[tempCode].cssFile
            });
        } catch(err){
            console.log('模板有问题::',tempMap[tempCode]);
            throw err;
        }
    }
}


/**
 *
 * @param assetsFIlePath
 * @param params
 * @returns {*}
 */
function extraTempCodeFromAssets(assetsFIlePath,params){

    let _fileNameTpl;
    if(assetsFIlePath.endsWith('.js')){
        _fileNameTpl=   outputJsFileNameTpl
    } else if(assetsFIlePath.endsWith('.css')){
        _fileNameTpl=  outputCssFileNameTpl
    }

    let _hash  = params.hash;

   let nameBegIndex = _fileNameTpl.indexOf('[name]');
   let nameEndIndex = nameBegIndex + "[name]".length;

    let begStr =_fileNameTpl.substring(0,nameBegIndex);
    let endStr =_fileNameTpl.substring(nameEndIndex);


    let _nameTemp = assetsFIlePath.replace(_hash,'[hash]');
    return  _nameTemp.replace(begStr,"").replace(endStr,"");
}

/**
 * 检验模板信息, 在模板索引中的内容
 */
// function * checkTemplateInfo(tempConfig,params){
//
//     let templateIndexPath;
//     templateIndexPath =  path.join(__dirname,'template-index/'+tempConfig.platForm+'-template-index.json');
//
//     let pcIndexArray = fse.readJSONSync(templateIndexPath);
//     let templateCode2Index = {};
//     for(let i =0,ilen =pcIndexArray.length;i<ilen;i++){
//         templateCode2Index[pcIndexArray[i].templateName] = i;
//     }
//
//
//     let _tempInfo  =extraTemplateInfo(tempConfig,params);
//     //对模板索引中的当前模板,修改其信息
//     if (templateCode2Index[tempConfig.templateName] >= 0) {
//         pcIndexArray[templateCode2Index[tempConfig.templateName]] = _tempInfo;
//     }else{
//         pcIndexArray.push(_tempInfo);
//     }
//
//     fse.outputJSONSync(templateIndexPath, pcIndexArray);
//     fse.outputFileSync(templateIndexPath.replace('.json','.js'),transfertpIndex2JsFile(pcIndexArray));
//     //envCode
//     //oss-hz.qianmi.com/x-site/prod/public/template-index
//
//     let uploadTask = [];
//     try{
//
//         uploadTask.push(ossClient.putObjectAbsolute(path.join(__dirname,params.jsFile),'x-site/'+envCode+'/public/'+params.jsFile));
//         uploadTask.push(ossClient.putObjectAbsolute(path.join(__dirname,params.cssFile),'x-site/'+envCode+'/public/'+params.cssFile));
//
//         uploadTask.push(ossClient.putObjectAbsolute(templateIndexPath,'x-site/'+envCode+'/public/template-index/'+tempConfig.platForm+'-template-index.json').then(response=>{
//             console.log('模板索引文件已更改并上传阿里云');
//         }));
//         uploadTask.push(ossClient.putObjectAbsolute(templateIndexPath.replace('.json','.js'),'x-site/'+envCode+'/public/template-index/'+tempConfig.platForm+'-template-index.js').then(response=>{
//             console.log('模板索引文件已更改并上传阿里云');
//         }));
//         yield uploadTask;
//     }catch(err){
//         console.error(err);
//
//     }
//     //上传阿里云
// }

/**
 * 提取模板信息
 */
function extraTemplateInfo(templateConfigInfo, params) {

    let acceptStyles = (templateConfigInfo.acceptStyles && templateConfigInfo.acceptStyles.map(item=> {
           return {name: item.name, title: item.title, background: item.background}
       })) || [];
    if(!templateConfigInfo.styleType ){
        templateConfigInfo.styleType ='none';
    }
    let styleType = templateConfigInfo.styleType;
    return {
        templateName: templateConfigInfo.templateName,
        id: templateConfigInfo.id,
        isShow: templateConfigInfo.isShow,
        templateName_cn: templateConfigInfo.templateName_cn,
        isDoublePlatformTpl: templateConfigInfo.isDoublePlatformTpl || false,
        pageCode: templateConfigInfo.pageCode,
        pageType: templateConfigInfo.pageType,
        platForm: templateConfigInfo.platForm,
        updateTime: templateConfigInfo.updateTime || '',
        systemCode: templateConfigInfo.systemCode,
        styleType,
        acceptStyles,
    }

}

function transfertpIndex2JsFile(templateIndexArray){

    return ` ;(function(){
        var tplIndex = ${JSON.stringify(templateIndexArray)};

        if(window.xDllContext && window.xDllContext.msg){
          window.xDllContext.msg.emit('XSite_template_index_loaded',tplIndex);
        } else if(window.__XSite_template_index_loaded){
          window.__XSite_template_index_loaded(tplIndex);
        } else {
          console.warn('未设置入口接收模板索引!!!');
        }
    })();
    `;
}

function readSyn() {
    process.stdin.pause();
    var response = fs.readSync(process.stdin.fd, 1000, 0, "utf8");
    process.stdin.resume();
    return response[0].trim();
}